import express from 'express';
import { body, validationResult, query, param } from 'express-validator';
import { Order } from '../models/index.js';
import { authenticateAdmin } from '../middleware/auth.js';
import { catchAsync, NotFoundError } from '../middleware/errorHandler.js';
import { success, paginated } from '../utils/response.js';

const router = express.Router();

// 手机端用户接口已移至 /api/mobile/orders/



// 管理员接口 - 获取订单列表
router.get('/admin/list',
  authenticateAdmin,
  [
    query('page').optional().isInt({ min: 1 }).withMessage('页码必须是正整数'),
    query('limit').optional().isInt({ min: 1, max: 100 }).withMessage('每页数量必须在1-100之间'),
    query('status').optional().isIn(['pending', 'paid', 'cancelled', 'refunded']).withMessage('状态参数无效'),
    query('user_id').optional().isInt({ min: 1 }).withMessage('用户ID必须是正整数'),
    query('quota_type').optional().isIn(['general', 'domain', 'expert']).withMessage('额度类型参数无效')
  ],
  catchAsync(async (req, res) => {
    const { page = 1, limit = 20, status, user_id, quota_type } = req.query;
    const where = {};
    
    if (status) where.status = status;
    if (user_id) where.user_id = parseInt(user_id);
    if (quota_type) where.quota_type = quota_type;
    
    const result = await Order.findAndCountAll({
      where,
      include: [
        { association: 'user', attributes: ['id', 'phone'] },
        { association: 'domain', attributes: ['id', 'name'] },
        { association: 'expert', attributes: ['id', 'nickname'] }
      ],
      order: [['created_at', 'DESC']],
      limit: parseInt(limit),
      offset: (parseInt(page) - 1) * parseInt(limit)
    });
    
    res.json(paginated(result.rows, {
      page: parseInt(page),
      limit: parseInt(limit),
      total: result.count,
      pages: Math.ceil(result.count / parseInt(limit))
    }, '获取订单列表成功'));
  })
);

// 管理员接口 - 订单统计
router.get('/admin/stats',
  authenticateAdmin,
  catchAsync(async (req, res) => {
    try {
      const stats = await Order.getStatistics();
      res.json(success(stats, '获取订单统计成功'));
    } catch (e) {
      // 兜底返回全为0
      res.json(success({ total: 0, pending: 0, paid: 0, cancelled: 0, totalAmount: 0 }, '获取订单统计成功'));
    }
  })
);

// 管理员接口 - 获取订单详情
router.get('/admin/:orderNo',
  authenticateAdmin,
  [
    param('orderNo').notEmpty().withMessage('订单号不能为空')
  ],
  catchAsync(async (req, res) => {
    const { orderNo } = req.params;
    
    const order = await Order.findByOrderNo(orderNo);
    if (!order) {
      throw new NotFoundError('订单不存在');
    }
    
    res.json(success({
      order
    }, '获取订单详情成功'));
  })
);


export default router;
